package 代码随想录.字符串.翻转字符串里的单词;

/**lc：151. 翻转字符串里的单词
 * linK：https://leetcode-cn.com/problems/reverse-words-in-a-string/
 * @author ChenweiLin
 * @create 2021-12-22 10:37
 */
public class ReverseWordsInaString {
    public static void main(String[] args) {
        String s =  "a good   example";
        String s1 = "  hello world  ";

        System.out.println("|"+reverseWords(s).toString()+"|");
        System.out.println("|"+reverseWords(s1).toString()+"|");

    }

    public static String reverseWords(String s) {
        //思路：双指针记录
        StringBuilder result = new StringBuilder();
        int fastIndex = s.length()-1;
        int lowIndex = s.length();

        for (; fastIndex >=0; fastIndex--) {
            //fast指针定格
            if((fastIndex == 0 && s.charAt(fastIndex) != ' ') || (s.charAt(fastIndex) != ' ' && s.charAt(fastIndex-1) ==  ' ')){
                //加入单词及空格
                String substring = s.substring(fastIndex, lowIndex);
                result.append(substring);
                result.append(' ');
            }

            //lowIndex 更新到上次fastIndex的位置
            if(s.charAt(fastIndex) == ' '){
                lowIndex = fastIndex;
            }
        }

        //移出最后一个空格
        StringBuilder stringBuilder = result.deleteCharAt(result.length() - 1);
        return new String(stringBuilder);
    }
}
